package cn.dogger.easyboot.kafka.utils;

import java.util.concurrent.TimeoutException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 生产者工具类
 * @author dogger
 * 2022/5/3 11:15
 */
@Component
public class KafkaProducerUtils<k,v> {

   private final Logger log;
   private final KafkaTemplate<k,v> kafkaTemplate;

    KafkaProducerUtils(KafkaTemplate<k, v> kafkaTemplate){
        this.kafkaTemplate = kafkaTemplate;
        log = LoggerFactory.getLogger(getClass());
    }

    /**
     * producer 同步方式发送数据
     *
     * @param topic   topic名称
     * @param message producer发送的数据
     */
    public void sendMessageSync(String topic,k key, v message) throws InterruptedException, ExecutionException, TimeoutException {
        kafkaTemplate.send(topic,key, message).get(10, TimeUnit.SECONDS);
    }

    /**
     * producer 异步方式发送数据
     *
     * @param topic   topic名称
     * @param message producer发送的数据
     */
    public void sendMessageAsync(String topic, v message) {
        kafkaTemplate.send(topic, message).addCallback(new ListenableFutureCallback() {
            @Override
            public void onFailure(Throwable throwable) {
                log.error("异步推送失败！");
            }

            @Override
            public void onSuccess(Object o) {
              log.info("异步推送成功！");

            }
        });
    }
}
